import React, { useState, useEffect } from "react"
import { Table, Button, Space, ImgDefault, Icon, message, Modal, Form, Radio, Checkbox, InputNumber, Spin, Select, Progress } from '@bytedance/mona-ui';
import { useAppSelector } from "~store"
// import { getProductList } from "~store/controller/autoCounps"

import GetForPageData from '@tools/toPageGetRequs'
import { getFlowProdectList, setGetConfig, getFlowTable } from '@Api/toNewPageApi/clearNotFlow'
import { get_lid } from "@Utils/getPageDecrypt"
import moment from 'moment';
import { getProductAllApi } from './pageTools'
import type { ColumnProps } from '@bytedance/mona-ui/es/components/table';
import { setProductStatus, deleteProduct } from "@Api/productApi"
import { get__token } from '@Utils/getPageDecrypt'
// import { useLiveQuery } from "dexie-react-hooks";
import db from "@tools/indexDB";
// import brotli, { decompress, compress } from 'brotli-wasm';
// import pako from 'pako';
// import XLSX, { read, writeFileXLSX, readFile } from "xlsx";
import * as XLSX from 'xlsx';
import { resolve } from "path";
const initApiConfig = {
    baseUrl: 'https://compass.jinritemai.com',
    timeout: 10000,
    pageUrl: 'https://compass.jinritemai.com/',
    title: '请打开电商罗盘后返回使用',
    // headers: {
    //     "Accept-Encoding": 'gzip',
    // },
    openUrl: 'https://compass.jinritemai.com/login/transfer?login_source=compass&mode=1&from_source=doudian_pc_web&redirect_url=https%3A%2F%2Fcompass.jinritemai.com%2Fshop%3Fbtm_ppre%3Da2427.b76571.c902327.d871297%26btm_pre%3Da2427.b76571.c4158.d20759_i3%26btm_show_id%3Dbab65aac-f8bc-496e-9cd2-644efdabb145%26'
}
const getInfoUrls = new GetForPageData(initApiConfig)


let allprodectData
let allDianshangLuopanData
function ProdectTabs() {
    // const dispacth = useAppDispatch()
    // const getprodectStatus: any = useAppSelector((state) => state.autoCounps.getprodectStatus)
    // const peodecuList: any = useAppSelector((state) => state.autoCounps.peodecuList)

    const [querDateTime, setQuerDateTime] = useState<any>({
        date_type: 23,
        end_date: moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD HH:mm:ss'),
        begin_date: moment().subtract(30, 'days').startOf('day').format('YYYY/MM/DD HH:mm:ss'),
        biter_str: `${moment().subtract(30, 'days').startOf('day').format('YYYY/MM/DD')} - ${moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD')}`
    })
    const [refoDataLodin, setRefoDataLodin] = useState(false)
    const [prodectList, setProdectList] = useState<any>([])
    const [clearConfig, setClearConfig] = useState({
        showO: true,
        showN: 0,
        clickO: false,
        clickN: 0,
        sellO: false,
        sellN: 0,

        baoliuO: false,
        baoliuN: 30
    })
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);

    const [cleartAllStatus, setCleartAllStatus] = useState<any>(false)

    const [nitClearProdects, setNitClearProdects] = useState<any>([])

    const [notClearBox, setNotClearBox] = useState<any>(false)
    const [prodectListRedous, setProdectListRedous] = useState<any>(0)
    const [getFlowLosiRedows, setGetFlowLosiRedows] = useState<any>(0)
    const [clearRedows, setClearRedows] = useState<any>(0)
    const [openTitleConttips, setOpenTitleConttips] = useState<any>('正在加载数据中， 请稍等')
    const [clearLogeStuas, setClearLogeStuas] = useState<any>(false)
    const shop_id = useAppSelector((state) => state.jinritemaiShops.userShopId)

    function initOpentEndCheackOpenUrlInfo(data) {
        console.log('打开进度 打开详情', data)
        if (!data) return
        setOpenTitleConttips(data.msg)
        if (data.type == 'success') {
            setRefoDataLodin(false)
            return
        }
        if (data.type === 'shopInfoNoter') {
            setRefoDataLodin(false)
            Modal.warning({
                title: '提示',
                content: data.msg,
                onOk() {
                    console.log('可以调用关闭所有电商罗盘的页面, 登陆过期也可以用')
                    // window.open('https://www.jinritemai.com/setting/shopInfo')
                },
            }
            )

            return
        }
        setRefoDataLodin(true)

    }

    function initFun() {

        let addInfoLimit = 0
        let getPredectListall = []
        let errpage = []
        let cletaerDtae
        let addLimitStop = 50
        let repeadter = 0
        let allPages = 0
        return new Promise(async (resolve, reject) => {
            let listAll: any = []

            const res = await getInfoUrls.init()
            if (res) {
                const setConfigStatus = await getInfoUrls.openReqU(setGetConfig(get_lid()))
                console.log('setConfigStatus', setConfigStatus)
                const data: any = {
                    page_no: 1,
                    page_size: 10,
                    date_type: querDateTime.date_type,
                    end_date: querDateTime.end_date,
                    begin_date: querDateTime.begin_date,

                }
                if (selectProderttype) {
                    data.product_status = 0
                }
                // getFlowList(data)
                const allDataFnu = await getPiLiangConter(data, (e) => {
                    console.log('e所有的结果', e)
                    setGetFlowLosiRedows(e)
                })
                console.log('allDataFnu', allDataFnu)
                resolve(allDataFnu)
                return
            }
            reject(false)
            // async function getFlowList(data) {

            //     const getEndData = await getInfoUrls.openReqU(getFlowProdectList(data))
            //     console.log('getEndData', getEndData)
            //     if (!getEndData.st) {
            //         if (!getEndData.data || !getEndData.data.length) {
            //             resolve(listAll)
            //             return
            //         }
            //         listAll.push(...getEndData.data)
            //         if (getEndData.page_result.total > data.page_size * data.page_no) {
            //             data.page_no++
            //             // console.log('lodinat', Math.ceil(getEndData.page_result.total / data.page_size), data.page_no)
            //             setGetFlowLosiRedows((data.page_no / Math.ceil(getEndData.page_result.total / data.page_size) * 100).toFixed(2))
            //             getFlowList(data)
            //             return
            //         }
            //         resolve(listAll)
            //         return
            //     }
            //     reject(false)
            //     console.log('请求失败', getEndData)
            // }


            function getPiLiangConter(shearDater, cobs) {
                // console.log('请求123456')
                errpage = []
                cletaerDtae = null
                addInfoLimit = 0
                addLimitStop = 50
                repeadter = 0
                allPages = 0
                allPages = 0
                return new Promise(async (resolve, reject) => {
                    const getEndData = await getInfoUrls.openReqU(getFlowProdectList(shearDater))
                    // console.log('getEndData', getEndData)
                    if (!getEndData.st) {
                        getPredectListall = getEndData.data || []
                        allPages = Math.ceil(getEndData.page_result.total / shearDater.page_size) - 1
                        if (getEndData.page_result.total <= 700) {
                            addLimitStop = 70
                            // addLimitStop = 70
                        }
                        getPredectMiter(getEndData.page_result.total, shearDater, (data) => {

                            resolve(data)
                        }, cobs)
                    }

                })
            }
            function getPredectMiter(total, shearDater, cb, cobs) {
                addInfoLimit = 0
                const getallData = []
                while ((shearDater.page_size * shearDater.page_no) < total && addInfoLimit < addLimitStop) {
                    // console.log('chetraer', ((shearDater.pageSize * (shearDater.page + 1)) < total) && (addInfoLimit < addLimitStop))
                    addInfoLimit += 1
                    shearDater.page_no++
                    // console.log('addNums', addInfoLimit, addLimitStop)
                    getallData.push(getInfoUrls.openReqU(getFlowProdectList(shearDater)).then(res => {
                        repeadter++
                        // console.log('统计进度', ((repeadter / allPages) * 100).toFixed(2) + '%')
                        cobs && cobs(((repeadter / allPages) * 100).toFixed(2))
                        Promise.resolve(res)
                        return res
                    }))
                }
                console.log('getallData', getallData)
                Promise.all(getallData).then(resit => {
                    // console.log('resit', resit)
                    resit.forEach(resdata => {
                        if (!resdata.code) {
                            resdata.data && resdata.data.length && getPredectListall.push(...resdata.data)
                        } else {
                            errpage.push({
                                config: resdata.config
                            })
                        }
                    })

                    if ((shearDater.page_size * shearDater.page_no) < total) {
                        cletaerDtae = setTimeout(_ => {
                            // console.log('继续获取', getPredectListall)
                            getPredectMiter(total, shearDater, cb, cobs)
                        }, 5000)
                        return
                    } else {
                        // console.log('获取完成', getPredectListall)
                        // const addProductList = {
                        //     create_time: Date.now(),
                        //     list: getPredectListall
                        // }
                        // localStorage.setItem('infoProdectList', JSON.stringify(addProductList))
                        cb && cb(getPredectListall)
                    }
                })
            }
        })
    }

    const [getLogsLoding, setGetLogsLoding] = useState(false)
    function getDbProdect() {
        setGetLogsLoding(true)
        db.clearFlowLog.where('shop_id').equals(shop_id).toArray().then((res) => {
            console.log('查询结果', res)
            setNitClearProdectsLogs(res)
            setClearLogeStuas(true)
            setGetLogsLoding(false)
        }).catch(err => {
            console.log('查询失败', err)
        })
    }


    const columnsData: ColumnProps<any>[] = [
        {
            title: '商品信息',
            key: '0',
            width: 300,
            // dataIndex: 'name',
            fixed: 'left',
            render: (text: any, record: any) => {
                // function TilpDater(content) {
                //     const texts = content.reject_reason

                //     return <div></div>
                // }
                return (
                    <Space direction="vertical">
                        <Space>
                            <ImgDefault
                                imgSrc={(() => {
                                    const imgae = record.img?.replace("obj/", "")
                                    return imgae + "~110x110_q75.image"
                                })()}
                                mask={false}
                                width={60}
                                height={60}></ImgDefault>
                            <Space direction="vertical" size={4}>
                                <div
                                    className="title"
                                    style={{
                                        fontSize: 12,
                                        color: "#252931"
                                    }}>
                                    {record.name}
                                </div>
                                <div
                                    className="isduer"
                                    style={{
                                        color: "#898b8f",
                                        fontSize: 12
                                    }}>
                                    ID:{record.product_id}
                                    <Icon
                                        type="CopyIcon"
                                        className="copyiconitem"
                                        style={{
                                            marginLeft: 5,
                                            cursor: "pointer"
                                        }}
                                        onClick={() => copyToClipboard(record.product_id)}
                                    />
                                </div>
                            </Space>
                        </Space>

                    </Space>
                )
            }
        },

        {
            title: '曝光人数',
            key: 'product_show_ucnt',
            dataIndex: 'product_show_ucnt',
            width: 120,
            sorter: {
                compare: (a, b) => a.product_show_ucnt - b.product_show_ucnt,
                multiple: 1,
            },
            // width: 80
        },
        {
            title: '点击人数',
            key: 'product_click_ucnt',
            dataIndex: 'product_click_ucnt',
            width: 120,
            sorter: {
                compare: (a, b) => a.product_click_ucnt - b.product_click_ucnt,
                multiple: 2,
            },
            // width: 80
        },
        {
            title: '销量',
            key: '1',
            dataIndex: 'sell_num',
            width: 80,
            sorter: {
                compare: (a, b) => a.sell_num - b.sell_num,
                multiple: 3,
            },
            // width: 80
        },
        {
            title: '创建天数',
            key: '1',
            dataIndex: 'day',
            width: 120,
            sorter: {
                compare: (a, b) => a.day - b.day,
                multiple: 4,
            },
            // width: 80
        },
        {
            title: '创建时间',
            key: '1',
            dataIndex: 'create_time',
            width: 170,

            sorter: {
                compare: (a, b) => new Date(a.create_time).getTime() - new Date(b.create_time).getTime(),
                multiple: 5,
            },
            // width: 80
        },
        {
            title: '价格',
            key: '2',
            width: 120,
            dataIndex: 'price'

        },
        {
            title: '库存',
            key: '3',
            width: 120,
            dataIndex: 'stock_num'
        },
        {
            title: '操作',
            key: '4',
            dataIndex: '4',
            fixed: 'right',
            width: 150,
            render: (text, record) => {
                // console.log('record', record)
                if (record.deleteStatus) {
                    return (<span style={{
                        color: 'red'
                    }}>商品已删除</span>)
                }
                return (

                    <Spin spinning={record.removedLodin || record.deleteLodin}>
                        {record.removedStatus ? <Button type="link" size="small" onClick={() => { deleteProductFunc([record.product_id]) }}>删除</Button> : <Space>
                            <Button type="link" icon={<Icon type="DeclineIcon"></Icon>} size="small" onClick={() => setProductStatusFunc([record.product_id])}>下架</Button>
                            <Button type="link" icon={<Icon type="DeleteIcon"></Icon>} size="small" onClick={() => { deleteProductFunc([record.product_id]) }}>下架并删除</Button>
                        </Space>}
                    </Spin>

                )
            }
        }
    ]

    const columnsDataNotClear: ColumnProps<any>[] = [
        {
            title: '商品信息',
            key: '0',
            width: 300,
            // dataIndex: 'name',
            fixed: 'left',
            render: (text: any, record: any) => {
                // function TilpDater(content) {
                //     const texts = content.reject_reason

                //     return <div></div>
                // }
                return (
                    <Space direction="vertical">
                        <Space>
                            <ImgDefault
                                imgSrc={(() => {
                                    const imgae = record.img?.replace("obj/", "")
                                    return imgae + "~110x110_q75.image"
                                })()}
                                mask={false}
                                width={60}
                                height={60}></ImgDefault>
                            <Space direction="vertical" size={4}>
                                <div
                                    className="title"
                                    style={{
                                        fontSize: 12,
                                        color: "#252931"
                                    }}>
                                    {record.name}
                                </div>
                                <div
                                    className="isduer"
                                    style={{
                                        color: "#898b8f",
                                        fontSize: 12
                                    }}>
                                    ID:{record.product_id}
                                    <Icon
                                        type="CopyIcon"
                                        className="copyiconitem"
                                        style={{
                                            marginLeft: 5,
                                            cursor: "pointer"
                                        }}
                                        onClick={() => copyToClipboard(record.product_id)}
                                    />
                                </div>
                            </Space>
                        </Space>

                    </Space>
                )
            }
        },

        {
            title: '曝光人数',
            key: 'product_show_ucnt',
            dataIndex: 'product_show_ucnt',
            width: 120,
            sorter: {
                compare: (a, b) => a.product_show_ucnt - b.product_show_ucnt,
                multiple: 1,
            },
            // width: 80
        },
        {
            title: '点击人数',
            key: 'product_click_ucnt',
            dataIndex: 'product_click_ucnt',
            width: 120,
            sorter: {
                compare: (a, b) => a.product_click_ucnt - b.product_click_ucnt,
                multiple: 2,
            },
            // width: 80
        },
        {
            title: '销量',
            key: '1',
            dataIndex: 'sell_num',
            width: 80,
            sorter: {
                compare: (a, b) => a.sell_num - b.sell_num,
                multiple: 3,
            },
            // width: 80
        },
        {
            title: '创建天数',
            key: '1',
            dataIndex: 'day',
            width: 120,
            sorter: {
                compare: (a, b) => a.day - b.day,
                multiple: 4,
            },
            // width: 80
        },
        {
            title: '创建时间',
            key: '1',
            dataIndex: 'create_time',
            width: 170,

            sorter: {
                compare: (a, b) => new Date(a.create_time).getTime() - new Date(b.create_time).getTime(),
                multiple: 5,
            },
            // width: 80
        },
        {
            title: '价格',
            key: '2',
            width: 120,
            dataIndex: 'price'

        },
        {
            title: '库存',
            key: '3',
            width: 120,
            dataIndex: 'stock_num'
        },
        // {
        //     title: '操作',
        //     key: '4',
        //     dataIndex: '4',
        //     fixed: 'right',
        //     width: 150,
        //     render: (text, record) => {
        //         // console.log('record', record)
        //         if (record.deleteStatus) {
        //             return (<span style={{
        //                 color: 'red'
        //             }}>商品已删除</span>)
        //         }
        //         return (

        //             <Spin spinning={record.removedLodin || record.deleteLodin}>
        //                 {record.removedStatus ? <Button type="link" size="small" onClick={() => { deleteProductFunc([record.product_id]) }}>删除</Button> : <Space>
        //                     <Button type="link" icon={<Icon type="DeclineIcon"></Icon>} size="small" onClick={() => setProductStatusFunc([record.product_id])}>下架</Button>
        //                     <Button type="link" icon={<Icon type="DeleteIcon"></Icon>} size="small" onClick={() => { deleteProductFunc([record.product_id]) }}>下架并删除</Button>
        //                 </Space>}
        //             </Spin>

        //         )
        //     }
        // }
    ]


    const columnsDataNotClearLogs: ColumnProps<any>[] = [
        {
            title: '商品信息',
            key: '0',
            width: 300,
            // dataIndex: 'name',
            fixed: 'left',
            render: (text: any, record: any) => {
                // function TilpDater(content) {
                //     const texts = content.reject_reason

                //     return <div></div>
                // }
                return (
                    <Space direction="vertical">
                        <Space>
                            <ImgDefault
                                imgSrc={(() => {
                                    const imgae = record.img?.replace("obj/", "")
                                    return imgae + "~110x110_q75.image"
                                })()}
                                mask={false}
                                width={60}
                                height={60}></ImgDefault>
                            <Space direction="vertical" size={4}>
                                <div
                                    className="title"
                                    style={{
                                        fontSize: 12,
                                        color: "#252931"
                                    }}>
                                    {record.name}
                                </div>
                                <div
                                    className="isduer"
                                    style={{
                                        color: "#898b8f",
                                        fontSize: 12
                                    }}>
                                    ID:{record.product_id}
                                    <Icon
                                        type="CopyIcon"
                                        className="copyiconitem"
                                        style={{
                                            marginLeft: 5,
                                            cursor: "pointer"
                                        }}
                                        onClick={() => copyToClipboard(record.product_id)}
                                    />
                                </div>
                            </Space>
                        </Space>

                    </Space>
                )
            }
        },

        // {
        //     title: '曝光人数',
        //     key: 'product_show_ucnt',
        //     dataIndex: 'product_show_ucnt',
        //     width: 120,
        //     sorter: {
        //         compare: (a, b) => a.product_show_ucnt - b.product_show_ucnt,
        //         multiple: 1,
        //     },
        //     // width: 80
        // },
        // {
        //     title: '点击人数',
        //     key: 'product_click_ucnt',
        //     dataIndex: 'product_click_ucnt',
        //     width: 120,
        //     sorter: {
        //         compare: (a, b) => a.product_click_ucnt - b.product_click_ucnt,
        //         multiple: 2,
        //     },
        //     // width: 80
        // },
        // {
        //     title: '销量',
        //     key: '1',
        //     dataIndex: 'sell_num',
        //     width: 80,
        //     sorter: {
        //         compare: (a, b) => a.sell_num - b.sell_num,
        //         multiple: 3,
        //     },
        //     // width: 80
        // },
        // {
        //     title: '创建天数',
        //     key: '1',
        //     dataIndex: 'day',
        //     width: 120,
        //     sorter: {
        //         compare: (a, b) => a.day - b.day,
        //         multiple: 4,
        //     },
        //     // width: 80
        // },
        {
            title: '创建时间',
            key: '1',
            dataIndex: 'create_time',
            width: 170,

            sorter: {
                compare: (a, b) => new Date(a.create_time).getTime() - new Date(b.create_time).getTime(),
                multiple: 5,
            },
            // width: 80
        },
        {
            title: '价格',
            key: '2',
            width: 120,
            dataIndex: 'price'

        },
        {
            title: '清理类型',
            key: '5',
            width: 120,
            render: (text, record) => {
                return record.type === 1 ? '下架' : '下架并删除'
            }
            // dataIndex: 'price'

        },
        // {
        //     title: '库存',
        //     key: '3',
        //     width: 120,
        //     dataIndex: 'stock_num'
        // },
        {
            title: '清理时间',
            key: '3',
            width: 120,
            dataIndex: 'clearTime'
        },
        // {
        //     title: '操作',
        //     key: '4',
        //     dataIndex: '4',
        //     fixed: 'right',
        //     width: 150,
        //     render: (text, record) => {
        //         // console.log('record', record)
        //         if (record.deleteStatus) {
        //             return (<span style={{
        //                 color: 'red'
        //             }}>商品已删除</span>)
        //         }
        //         return (

        //             <Spin spinning={record.removedLodin || record.deleteLodin}>
        //                 {record.removedStatus ? <Button type="link" size="small" onClick={() => { deleteProductFunc([record.product_id]) }}>删除</Button> : <Space>
        //                     <Button type="link" icon={<Icon type="DeclineIcon"></Icon>} size="small" onClick={() => setProductStatusFunc([record.product_id])}>下架</Button>
        //                     <Button type="link" icon={<Icon type="DeleteIcon"></Icon>} size="small" onClick={() => { deleteProductFunc([record.product_id]) }}>下架并删除</Button>
        //                 </Space>}
        //             </Spin>

        //         )
        //     }
        // }
    ]
    const [nitClearProdectsLogs, setNitClearProdectsLogs] = useState<any>([])
    function copyToClipboard(text) {
        navigator.clipboard
            .writeText(text)
            .then(function () {
                message.success("复制成功")
            })
            .catch(function (err) {
                message.error("复制失败")
            })
    }
    const [selectProderttype, setSelectProderttype] = useState(1)
    let addFlowListData = []
    function getFlowListTab() {
        addFlowListData = []
        setGetFlowLosiRedows(30)
        return new Promise(async (resolve, reject) => {
            const setConfigStatus = await getInfoUrls.openReqU(setGetConfig(get_lid()))
            setGetFlowLosiRedows(50)
            getInfoUrls.openReqU(getFlowTable({
                file_name: `商品卡列表数据_${querDateTime.biter_str}~${querDateTime.end_date}.xlsx`,
                req_json_str: JSON.stringify({ "date_type": querDateTime.date_type, "end_date": querDateTime.end_date, "begin_date": querDateTime.begin_date, "category_code": ["all"] })
            })).then(res => {
                console.log('表格数据', res)
                setGetFlowLosiRedows(100)
                res.forEach((item) => {
                    addFlowListData.push({
                        prodect_id: item['商品ID'],
                        product_show_ucnt: item['商品卡曝光人数'],
                        product_click_ucnt: item['商品卡点击人数']
                    })
                })
                resolve(addFlowListData)

            })
        })

    }
    async function runClearDataInfos() {
        allprodectData = null
        allDianshangLuopanData = null
        addFlowListData = null
        setProdectListRedous(0)
        setGetFlowLosiRedows(0)
        setClearRedows(0)
        const res = await getInfoUrls.init(initOpentEndCheackOpenUrlInfo)
        if (!res) return
        // getFlowListTab()
        // return
        setOpenTitleConttips('正在加载数据中， 请稍等')
        const shearDataAlls = {}
        switch (selectProderttype) {
            case 0:
                shearDataAlls['check_status'] = ''
                break;
            case 1:
                shearDataAlls['check_status'] = 3
                shearDataAlls['status'] = 0
                shearDataAlls['has_stock'] = 1
                shearDataAlls['order_field'] = 'audit_time'
                shearDataAlls['is_online'] = 1
                break;
            case 2:
                shearDataAlls['order_field'] = 'offline_time'
                shearDataAlls['is_online'] = ''
                shearDataAlls['is_offline'] = 1
                break;
            default:
                break;
        }
        const shearDater = {
            page: 0,
            pageSize: 20,

            business_type: 4,
            is_online: 1,
            not_for_sale_search_type: 1,
            ...shearDataAlls
        }
        setRefoDataLodin(true)
        const indengterPromisAll = [getProductAllApi(shearDater, (reter) => {
            // console.log('回传商品进度', reter)
            setProdectListRedous(reter)
        }).then(res => {
            allprodectData = res
            // .map(item => {
            //     item.product_show_ucnt = 0
            //     item.product_click_ucnt = 0
            //     return item
            // })
            setProdectListRedous(100)
            Promise.resolve(res)
            return res
        }).catch(err => {
            message.error('获取商品列表失败')
            Promise.reject(err)
            return err
        })]
        if (querDateTime.date_type !== 1) {
            indengterPromisAll.push(getFlowListTab().then((res: any) => {
                // console.log('re1223468---s', res)
                allDianshangLuopanData = res
                // console.log('有流量的数据---***', allDianshangLuopanData)
                setGetFlowLosiRedows(100)

                Promise.resolve(res)
                return res
            }).catch(err => {
                message.error('获取电商罗盘流量失败')
                Promise.reject(err)
                return err
            }))
        } else {
            indengterPromisAll.push(initFun().then((res: any) => {
                // console.log('re1223468---sshishi', res)
                allDianshangLuopanData = res.map((item) => {
                    return {
                        prodect_id: item.cell_info?.product?.product_id_value?.value.value_str,
                        product_show_ucnt: item.cell_info?.product_show_ucnt?.product_show_ucnt_index_values?.index_values.value.value || 0,
                        product_click_ucnt: item.cell_info?.product_click_ucnt?.product_click_ucnt_index_values?.index_values.value.value || 0
                    }
                })
                // console.log('有流量的数据', allDianshangLuopanData)
                setGetFlowLosiRedows(100)
                // console.log('有流量的数据---66666-----***', allDianshangLuopanData)
                Promise.resolve(res)
                return res
            }).catch(err => {
                message.error('获取电商罗盘流量失败')
                Promise.reject(err)
                return err
            }))
        }

        Promise.all(indengterPromisAll).then((res) => {
            setRefoDataLodin(false)
            formatClearNotFlowData()
        })
    }
    useEffect(() => {
        if (allDianshangLuopanData && allprodectData) {
            formatClearNotFlowData()
        }
    }, [clearConfig])
    function formatClearNotFlowData() {
        if (!allprodectData || !allDianshangLuopanData) return message.error('数据获取错误 清稍后再试')
        // const binterData = allDianshangLuopanData.map((item, index) => {

        //     return {
        //         prodect: (() => {
        //             const dataFoers = {}
        //             item.cell_info?.product && Object.keys(item.cell_info?.product).forEach((key) => {
        //                 dataFoers[key] = item.cell_info?.product[key].value?.value_str || item.cell_info?.product[key].value?.value
        //             })
        //             return dataFoers
        //         })(),
        //         product_show_ucnt: {
        //             value: item.cell_info?.product_show_ucnt?.product_show_ucnt_index_values?.index_values.value.value || 0,
        //             out_period_ratio: item.cell_info?.product_show_ucnt?.product_show_ucnt_index_values?.index_values.out_period_ratio.value || 0,
        //         },
        //         product_click_ucnt: {
        //             value: item.cell_info?.product_click_ucnt?.product_click_ucnt_index_values?.index_values.value.value || 0,
        //             out_period_ratio: item.cell_info?.product_click_ucnt?.product_click_ucnt_index_values?.index_values.out_period_ratio.value || 0,
        //         }
        //     }
        // })
        // console.log('flowList123456', JSON.stringify(allDianshangLuopanData))
        // 合并数据
        const allprodectDataAll = allprodectData.map((item) => {
            item.product_show_ucnt = 0
            item.product_click_ucnt = 0
            // console.log('item6666', item)
            const findProdectInFlow = allDianshangLuopanData.find((itemB) => {
                return itemB.prodect_id === item.product_id
            })
            // console.log('findProdectInFlow', findProdectInFlow)
            if (findProdectInFlow) {
                item.product_show_ucnt = findProdectInFlow.product_show_ucnt
                item.product_click_ucnt = findProdectInFlow.product_click_ucnt
            }
            item.removedStatus = item.removedStatus || false
            item.removedLodin = item.removedLodin || false
            item.deleteStatus = item.deleteStatus || false
            item.deleteLodin = item.deleteLodin || false
            return item
        })

        filterListerData()
        function filterListerData() {
            const isBaoliuO = clearConfig.baoliuO ? allprodectDataAll.filter((item) => {
                return item.day > clearConfig.baoliuN
            }) : allprodectDataAll

            const filterShowO = clearConfig.showO ? isBaoliuO.filter((item) => {
                return item.product_show_ucnt <= clearConfig.showN
            }) : isBaoliuO
            const filterClickO = clearConfig.clickO ? filterShowO.filter((item) => {
                return item.product_click_ucnt <= clearConfig.clickN
            }) : filterShowO
            const filterSellO = clearConfig.sellO ? filterClickO.filter((item) => {
                return item.sell_num <= clearConfig.sellN
            }) : filterClickO
            const notClearList = allprodectDataAll.filter((item) => {
                return !filterSellO.find((itemB) => {
                    return itemB.product_id === item.product_id
                })
            })
            // console.log('无需清理', notClearList)
            setNitClearProdects(notClearList)
            setProdectList(filterSellO)
        }
    }
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        // console.log('selectedRowKeys changed: ', selectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
        getCheckboxProps: (record) => ({
            disabled: record.deleteStatus, // Column configuration not to be checked
            name: record.product_id,
        }),
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE
        ]
    };
    function setProductStatusFunc(ids: string[], cb?) {
        if (!cheackBuyContent()) return
        // db.clearFlowLog.where('shop_id').equals(shop_id).toArray().then((res) => {
        //     console.log('更新成功0000', res)
        // })

        // return
        // console.log('getListItem', getListItem)

        // return
        setProdectList((item) => {
            return item.map((item) => {
                if (ids.includes(item.product_id)) {
                    item.removedLodin = true
                }
                return item
            })
        })
        // x-www-form-urlencoded
        const searchParams = new URLSearchParams();
        searchParams.append('appid', '1');
        searchParams.append('__token', get__token().__token);
        searchParams.append('_bid', 'ffa_goods');
        searchParams.append('_lid', get_lid() + '');
        ids.forEach((id) => {
            searchParams.append('product_ids[]', id);
        })
        setProductStatus(searchParams).then((res: any) => {
            if (!res.code) {
                !cb && message.success('操作成功')
                const getListItem = prodectList.filter((item) => {
                    item.shop_id = shop_id
                    item.type = 1 // 1下架 2删除
                    console.log('item.shop_id', item.shop_id)
                    item.clearTime = moment().format('YYYY-MM-DD HH:mm:ss')
                    return ids.includes(item.product_id)
                })
                db.clearFlowLog.bulkAdd(getListItem).then((res) => {
                    console.log('保存成功', res)

                })
                setProdectList((item) => {
                    return item.map((item) => {
                        if (ids.includes(item.product_id)) {
                            item.removedStatus = true
                            item.removedLodin = false
                        }
                        return item
                    })
                })
                cb && cb(true)
                // initFun()
            } else {
                message.error(res.msg)
                setProdectList((item) => {
                    return item.map((item) => {
                        if (ids.includes(item.product_id)) {
                            // item.removedStatus = true
                            item.removedLodin = false
                        }
                        return item
                    })
                })
                cb && cb(false)
            }
        })
    }

    function deleteProductFunc(ids: string[], cb?) {
        if (!cheackBuyContent()) return
        setProdectList((item) => {
            return item.map((item) => {
                if (ids.includes(item.product_id)) {
                    item.deleteLodin = true
                }

                return item
            })
        })


        // x-www-form-urlencoded
        const searchParams = new URLSearchParams();
        searchParams.append('appid', '1');
        searchParams.append('__token', get__token().__token);
        searchParams.append('_bid', 'ffa_goods');
        searchParams.append('_lid', get_lid() + '');
        ids.forEach((id) => {
            searchParams.append('product_ids[]', id);
        })
        deleteProduct(searchParams).then((res: any) => {
            if (!res.code) {
                !cb && message.success('操作成功')
                const getListItem = prodectList.filter((item) => {
                    item.shop_id = shop_id
                    item.type = 2 // 1下架 2删除
                    item.clearTime = moment().format('YYYY-MM-DD HH:mm:ss')
                    console.log('item.shop_id', item.shop_id)
                    return ids.includes(item.product_id)
                })
                db.clearFlowLog.bulkAdd(getListItem).then((res) => {
                    console.log('保存成功', res)

                })
                setProdectList((item) => {
                    return item.map((item) => {
                        if (ids.includes(item.product_id)) {
                            item.removedStatus = true
                            item.deleteStatus = true
                            item.deleteLodin = false
                            setSelectedRowKeys((items: any) => {
                                return items.filter((uids) => !ids.includes(uids))
                            })
                        }
                        return item
                    })
                })
                cb && cb(true)
                // initFun()
            } else {
                message.error(res.msg)
                setProdectList((item) => {
                    return item.map((item) => {
                        if (ids.includes(item.product_id)) {
                            item.deleteLodin = false
                        }
                        return item
                    })
                })
                cb && cb(false)
            }
        })
    }
    function setProductStatusFuncAll(type) {
        if (!cheackBuyContent()) return
        setClearRedows(0)

        const copyData = JSON.parse(JSON.stringify(selectedRowKeys))
        setCleartAllStatus(true)
        clearFunfder(copyData)
        function clearFunfder(data) {
            const clearItemList = data.splice(0, 20) //最多100个
            if (!clearItemList || !clearItemList.length) {
                setCleartAllStatus(false)
                return message.success('操作完成')
            }
            // console.log('selectedRowKeys', selectedRowKeys.length, data.length, selectedRowKeys.length - data.length, ((selectedRowKeys.length - data.length) / selectedRowKeys.length * 100).toFixed(2))
            setClearRedows(((selectedRowKeys.length - data.length) / selectedRowKeys.length * 100).toFixed(2))
            type === 1 ? setProductStatusFunc(clearItemList, (res) => {
                if (res) {
                    clearFunfder(data)

                    return
                }
                setCleartAllStatus(false)
                message.error('操作失败 请联系客服处理')
            }) : deleteProductFunc(clearItemList, (res) => {
                if (res) {
                    clearFunfder(data)
                    return
                }
                setCleartAllStatus(false)
                message.error('操作失败 请联系客服处理')
            })
        }
    }
    const isBuyStatus = useAppSelector(
        (state) => state.jinritemaiProduct.isBuyStatus
    )
    function cheackBuyContent() {
        if (isBuyStatus.status) {
            // if (!show) {
            Modal.confirm({
                title: isBuyStatus.title,
                content: isBuyStatus.content,
                icon: null,
                okText: isBuyStatus.okText,
                cancelText: " 取消",
                onOk: () => {
                    open(isBuyStatus.url)
                    return
                }
            })
            return false
            // }

        }
        return true
    }



    return <>
        {/* <Button onClick={() => {
            dispacth(getProductList(true))
        }}>刷新店铺商品列表</Button>
        <Button type="primary" onClick={() => {
            initFun()
        }}>测试请求</Button> */}
        <Space direction="vertical" size={8} style={{
            padding: '10px 0',
            width: '100%'
        }}>
            <Form size="small">
                <Form.Item label="流量统计时间">
                    <Space>
                        <div className="times" style={{
                            width: 200,
                            textAlign: 'right'
                        }}>
                            {querDateTime.biter_str}
                        </div>

                        <Radio.Group value={querDateTime.date_type} onChange={async (e) => {
                            const res = await getInfoUrls.init()
                            if (!res) return
                            querDateTime.date_type = e.target.value
                            switch (e.target.value) {
                                case 1:
                                    querDateTime.begin_date = moment().startOf('day').format('YYYY/MM/DD HH:mm:ss')
                                    querDateTime.end_date = moment().startOf('day').format('YYYY/MM/DD HH:mm:ss')
                                    querDateTime.biter_str = moment().format('YYYY/MM/DD HH:mm:ss')
                                    break;
                                case 20:
                                    querDateTime.begin_date = moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD HH:mm:ss')
                                    querDateTime.end_date = moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD HH:mm:ss')
                                    querDateTime.biter_str = `${moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD')} - ${moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD')}`
                                    break;
                                case 21:
                                    querDateTime.begin_date = moment().subtract(7, 'days').startOf('day').format('YYYY/MM/DD HH:mm:ss')
                                    querDateTime.end_date = moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD HH:mm:ss')
                                    querDateTime.biter_str = `${moment().subtract(7, 'days').startOf('day').format('YYYY/MM/DD')} - ${moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD')}`
                                    break;
                                case 23:
                                    querDateTime.begin_date = moment().subtract(30, 'days').startOf('day').format('YYYY/MM/DD HH:mm:ss')
                                    querDateTime.end_date = moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD HH:mm:ss')
                                    querDateTime.biter_str = `${moment().subtract(30, 'days').startOf('day').format('YYYY/MM/DD')} - ${moment().subtract(1, 'days').startOf('day').format('YYYY/MM/DD')}`
                                    break;
                                default:
                                    break;
                            }
                            setQuerDateTime({ ...querDateTime })
                            // initFun()

                        }}>
                            <Radio.Button value={1}>实时</Radio.Button>
                            <Radio.Button value={20}>近1天</Radio.Button>
                            <Radio.Button value={21}>近7天</Radio.Button>
                            <Radio.Button value={23}>近30天</Radio.Button>
                        </Radio.Group>
                    </Space>
                </Form.Item>

                <Form.Item label="清理条件">
                    <Space>
                        <Space size={2}>
                            <Checkbox checked={clearConfig.showO} onChange={(e) => {
                                setClearConfig({
                                    ...clearConfig,
                                    showO: e.target.checked
                                })
                            }}>清理曝光人数≤</Checkbox>
                            <InputNumber value={clearConfig.showN} disabled={!clearConfig.showO} onChange={(e: any) => {
                                setClearConfig({
                                    ...clearConfig,
                                    showN: e
                                })
                            }} style={{
                                width: '100px'
                            }} unit="次" min={0} />
                            {/* <div className="title"></div> */}

                        </Space>
                        <Space size={2}>
                            <Checkbox checked={clearConfig.clickO} onChange={(e) => {
                                setClearConfig({
                                    ...clearConfig,
                                    clickO: e.target.checked
                                })
                            }}>清理点击人数≤</Checkbox>
                            <InputNumber value={clearConfig.clickN} disabled={!clearConfig.clickO} onChange={(e: any) => {
                                setClearConfig({
                                    ...clearConfig,
                                    clickN: e
                                })
                            }} style={{
                                width: '100px'
                            }} unit="次" min={0} />
                            {/* <div className="title"></div> */}

                        </Space>
                        <Space size={2}>
                            <Checkbox checked={clearConfig.sellO} onChange={(e) => {
                                setClearConfig({
                                    ...clearConfig,
                                    sellO: e.target.checked
                                })
                            }}>清理销量≤</Checkbox>
                            <InputNumber value={clearConfig.sellN} disabled={!clearConfig.sellO} onChange={(e: any) => {
                                setClearConfig({
                                    ...clearConfig,
                                    sellN: e
                                })
                            }} style={{
                                width: '100px'
                            }} unit="单" min={0} />
                            {/* <div className="title"></div> */}

                        </Space>
                    </Space>
                </Form.Item>

                <Form.Item label="跳过条件">
                    <Space>
                        <Space size={2}>
                            <Checkbox checked={clearConfig.baoliuO} onChange={(e) => {
                                setClearConfig({
                                    ...clearConfig,
                                    baoliuO: e.target.checked
                                })
                            }}>保留铺货时间≤</Checkbox>
                            <InputNumber value={clearConfig.baoliuN} disabled={!clearConfig.baoliuO} onChange={(e: any) => {
                                setClearConfig({
                                    ...clearConfig,
                                    baoliuN: e
                                })
                            }} style={{
                                width: '100px'
                            }} unit="天" min={0} />
                            {/* <div className="title"></div> */}

                        </Space>

                    </Space>
                </Form.Item>

                <Form.Item noStyle>
                    <Space>
                        <Space>
                            <span>清理范围：</span>
                            <Select style={{
                                width: 150
                            }} value={selectProderttype} disabled={refoDataLodin || cleartAllStatus} onChange={(e: any) => {
                                console.log(e)
                                setSelectProderttype(e)
                            }}>
                                <Select.Option value={0}>全部</Select.Option>
                                <Select.Option value={1}>在售卖</Select.Option>
                                <Select.Option value={2}>仓库中</Select.Option>
                            </Select>
                        </Space>
                        <Button type="primary" disabled={refoDataLodin || cleartAllStatus} onClick={runClearDataInfos} loading={refoDataLodin || cleartAllStatus}>开始筛选</Button>
                        <Button type="primary" disabled={refoDataLodin || cleartAllStatus || !selectedRowKeys.length} icon={<Icon type="DeclineIcon"></Icon>}
                            loading={refoDataLodin || cleartAllStatus}
                            onClick={() => {
                                setProductStatusFuncAll(1)
                            }}
                        >下架({selectedRowKeys.length}/{prodectList.length})</Button>
                        <Button type="primary" disabled={refoDataLodin || cleartAllStatus || !selectedRowKeys.length} icon={<Icon type="DeleteIcon"></Icon>}
                            loading={refoDataLodin || cleartAllStatus}
                            onClick={() => {
                                setProductStatusFuncAll(2)
                            }}
                        >下架并删除({selectedRowKeys.length}/{prodectList.length})</Button>
                        {!!nitClearProdects.length && <Button type="link" onClick={() => {
                            setNotClearBox(true)
                        }}>无需清理商品{nitClearProdects.length}个</Button>}
                    </Space>
                </Form.Item>

                <Form.Item label="进度">
                    <Space direction="vertical">
                        <Space size={2}>
                            <span>获取商品进度:</span>
                            {/* <div className="rederwe">

                            </div> */}
                            <Progress percent={prodectListRedous} style={{
                                width: 200
                            }} />

                        </Space>
                        <Space size={2}>
                            <span>获取流量进度:</span>
                            {/* <div className="rederwe">

                            </div> */}
                            <Progress percent={getFlowLosiRedows} style={{
                                width: 200
                            }} />

                        </Space>

                        <Space size={2}>
                            <span>清理进度:</span>
                            {/* <div className="rederwe">

                            </div> */}
                            <Progress percent={clearRedows} style={{
                                width: 200
                            }} />

                        </Space>
                    </Space>
                </Form.Item>
            </Form>

            <Table
                rowSelection={rowSelection}
                loading={{
                    spinning: refoDataLodin || cleartAllStatus,
                    tip: openTitleConttips
                }}
                // 加载中的提示文案
                // loadingTip="正在获取商品数据" 
                scroll={{ y: 800, x: 800 }}
                title={() => {
                    return <div style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center'
                    }}>
                        <span>
                            {'待清理无流量商品' + prodectList.length + '个'}
                        </span>
                        <Space>
                            <Button size="mini" onClick={() => {
                                console.log('查看清理历史')
                                getDbProdect()
                            }}>清理历史</Button>
                        </Space>
                    </div>
                }}
                columns={columnsData}
                rowKey="product_id"
                dataSource={prodectList}
                pagination={{
                    total: prodectList.length,
                    showTotal: (total, range) => {
                        return `共 ${total} 条`
                    }
                }} />


        </Space>
        <Modal
            title="无需清理商品"
            width={1100}
            // style={{
            //     height: 800
            // }}
            footer={null}
            onCancel={() => setNotClearBox(false)}
            visible={notClearBox}
        >
            <Table
                // rowSelection={rowSelection}
                // loading={refoDataLodin || cleartAllStatus}
                // scroll={{ y: 600 }}

                columns={columnsDataNotClear}
                rowKey="product_id"
                dataSource={nitClearProdects}
                pagination={{
                    total: nitClearProdects.length,
                    showTotal: (total, range) => {
                        return `共 ${total} 条`
                    }
                }} />

        </Modal>

        <Modal
            title="清理历史记录"
            width={1100}
            // style={{
            //     height: 800
            // }}
            footer={null}
            onCancel={() => setClearLogeStuas(false)}
            visible={clearLogeStuas}
        >
            <Table
                // rowSelection={rowSelection}
                // loading={refoDataLodin || cleartAllStatus}
                // scroll={{ y: 600 }}
                loading={getLogsLoding}
                columns={columnsDataNotClearLogs}
                rowKey="product_id"
                dataSource={nitClearProdectsLogs}
                pagination={{
                    total: nitClearProdectsLogs.length,
                    showTotal: (total, range) => {
                        return `共 ${total} 条`
                    }
                }} />

        </Modal>


    </>
}
export default ProdectTabs